import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
    {
      path: '/mes',
      name: 'mes-management',
      component: () => import('../views/MESManagement.vue'),
      meta: { requiresAuth: true }
    },
  ],
})

// 简单的身份验证检查
const isAuthenticated = () => {
  // 这里可以检查 localStorage、sessionStorage 或 Pinia store 中的登录状态
  return localStorage.getItem('isLoggedIn') === 'true'
}

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要身份验证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查用户是否已登录
    if (!isAuthenticated()) {
      // 未登录，重定向到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 保存原始路径用于登录后重定向
      })
    } else {
      next() // 已登录，继续访问
    }
  } else {
    next() // 不需要身份验证的路由，直接访问
  }
})

export default router
